package cn.tedu._03vehicle.base.interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class RateLimitInterceptor implements HandlerInterceptor {

    private static final int MAX_REQUEST_COUNT = 3;
    private static final int REQUEST_TIME_WINDOW_SIZE = 60;

    private final ConcurrentHashMap<String, Integer> clientCounts = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String, LocalDateTime> lastRequestTimes = new ConcurrentHashMap<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.debug("开始网络限流拦截器");
        String clientIp = request.getRemoteAddr();
        LocalDateTime lastTime = lastRequestTimes.get(clientIp);
        if(lastTime == null || LocalDateTime.now().isAfter(lastTime.plusSeconds(REQUEST_TIME_WINDOW_SIZE))) {
            clientCounts.put(clientIp, 0);
            lastRequestTimes.put(clientIp, LocalDateTime.now());
        }
        Integer i = clientCounts.get(clientIp);
        i += 1;
        clientCounts.put(clientIp, i);
        if(i > MAX_REQUEST_COUNT){
            throw new RuntimeException("访问过于繁忙，请稍后再试");
        }
        return true;
    }
}
